package cn.it.service.impl;

import cn.it.dao.RoleDao;
import cn.it.entity.PageResult;
import cn.it.entity.QueryPageBean;
import cn.it.pojo.Permission;
import cn.it.pojo.Role;
import cn.it.pojo.User;
import cn.it.service.RoleService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer userId) {
        return roleDao.findRoleIdsByUserId(userId);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<Role> page = roleDao.selectByCondition(queryString);

        long total = page.getTotal();
        List<Role> list = page.getResult();
        return new PageResult(total, list);
    }

    @Override
    public List<Permission> findAllPermission() {
        return roleDao.findByPermission();
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }

    @Override
    public void add(Integer[] permissionIds, Role role) {

        roleDao.add(role);

        Integer roleId = role.getId();

        for (Integer permissionId : permissionIds) {
            Map<String,Integer> map =new HashMap<>();
            map.put("role_id",roleId);
            map.put("permission_id",permissionId);
            roleDao.setRoleIdAndPermissionId(map);
        }

    }

    @Override
    public void edit(Role role, Integer[] permissionIds) {
        roleDao.edit(role);

        Integer roleId = role.getId();

        roleDao.deleteRoleId(roleId);

        for (Integer permissionId : permissionIds) {
            Map<String,Integer> map =new HashMap<>();
            map.put("role_id",roleId);
            map.put("permission_id",permissionId);
            roleDao.setRoleIdAndPermissionId(map);
        }
    }

    @Override
    public void deleteById(Integer id) {

        roleDao.deleteRoleId(id);

        roleDao.deletRoles(id);
    }
}
